package com.example.anydo.net;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.util.Log;

import com.example.anydo.R;
import com.example.anydo.util.pub_util.LoadingPlayer;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RequestBuilder {

    LoadingPlayer player;

    private HashMap<String,String> params;
    private String url;
    private OkHttpClient client;
    private Class clazz;

    private String TAG = "HttpRequest";
    private Activity activity;

    private String responseJson = "";
    private String msg;

    public RequestBuilder(String url, OkHttpClient client) {
        params = new HashMap<>();
        this.url = url;
        this.client = client;
    }

    public RequestBuilder activity(Activity activity){
        this.activity = activity;

        return this;
    }

    public RequestBuilder setPlayer(String msg){
        if(activity == null){
            throw new RuntimeException("activity not init!");
        }
        this.msg = msg;
        player = new LoadingPlayer(activity);
        return this;
    }

    public RequestBuilder addParams(String key, String value){
        params.put(key,value);
        return this;
    }

    public <T> RequestBuilder asObject(Class<T> clazz) {
        this.clazz = clazz;
        return this;
    }

    public <T> void doGet(final DataBack<T> dataBack){
        // 开始动画
        if(player != null){
            player.loading(msg);
        }

        Request.Builder builder = new Request.Builder();
        url += "?";
        for(Map.Entry<String,String> entry : params.entrySet()){
            url += entry.getKey() + "=";
            url += entry.getValue();
            url += "&";
        }
        Log.e(TAG, "doGet: " + url );
        final Request request = builder.url(url)
                .get()
                .build();
        final Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(@NotNull Call call, @NotNull final Response response){

                responseJson = "";
                try {
                    responseJson = response.body().string();
                    Log.e(TAG, "onResponse: "+ responseJson);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Gson gson = new Gson();
                        T data = (T) gson.fromJson(responseJson,clazz);

                        dataBack.onResponse(data);
                        if(player!=null){
                            player.dismiss();

                        }
                    }
                });
            }
            @Override
            public void onFailure(@NotNull Call call, @NotNull final IOException e) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e(TAG, "onFailure: "+ e.getMessage() );
                        dataBack.onFailure(e.getMessage());
                        if(player!=null){
                            player.dismiss();

                        }
                    }
                });

            }
        });
    }

    public <T> void doJsonPost(String postJson,final DataBack<T> dataBack){
        // 开始动画
        if(player != null){
            player.loading(msg);
        }

        RequestBody body = RequestBody.create(postJson,
                MediaType.parse("application/json;charset=utf-8"));

        Request.Builder builder = new Request.Builder();
        url += "?";
        for(Map.Entry<String,String> entry : params.entrySet()){
            url += entry.getKey() + "=";
            url += entry.getValue();
            url += "&";
        }

        Log.e(TAG, "doPost: " + url );
        final Request request = builder
                .url(url)
                .post(body)
                .build();

        final Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(@NotNull Call call, @NotNull final Response response){
                responseJson = "";
                try {
                    responseJson = response.body().string();
                    Log.e(TAG, "onResponse: "+ responseJson);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Gson gson = new Gson();
                        T data = (T) gson.fromJson(responseJson,clazz);
                        dataBack.onResponse(data);
                        if(player != null){
                            player.dismiss();
                        }
                    }
                });
            }
            @Override
            public void onFailure(@NotNull Call call, @NotNull final IOException e) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e(TAG, "onFailure: "+ e.getMessage() );
                        dataBack.onFailure(e.getMessage());
                        if(player != null){
                            player.dismiss();
                        }
                    }
                });

            }
        });
    }
}
